import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 19182
 * Date: 2025-10-08
 * Time: 21:01
 */
public class TcpEchoServer {
    private ServerSocket serverSocket = null;
    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动");
        while(true){
            Socket socket = serverSocket.accept();
            ExecutorService executorService = Executors.newCachedThreadPool();
            executorService.submit(()->{
                try {
                    processConection(socket);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
        }
    }
    private void processConection(Socket socket) throws IOException {
        System.out.printf("[%s:%d]客户端上线", socket.getInetAddress(), socket.getPort());
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();
            Scanner scanner = new Scanner(inputStream);
            PrintWriter writer = new PrintWriter(outputStream)){
            while(true) {    //一个连接，多个请求
                    if(!scanner.hasNext()){
                        System.out.printf("[%s:%d]客户端下线!\n", socket.getInetAddress(), socket.getPort());
                        break;
                    }
                    String request = scanner.next();
                    String response = process(request);
                    writer.println(response);
                    writer.flush(); //刷新缓冲区
                  System.out.printf("[%s:%d] req:%s, req:%s\n", socket.getInetAddress(), socket.getPort(), request, response);
            }
        }finally {
            socket.close(); //一次连接通信完成后，要关闭连接
        }

    }
    private String process(String request){
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer tcpEchoServer = new TcpEchoServer(9090);
        tcpEchoServer.start();
    }
}
